//
//  ClassViewController.m
//  Feel_at_home
//
//  Created by dlios on 15/9/23.
//  Copyright © 2015年 Feel_at_home. All rights reserved.
//

#import "ClassViewController.h"
#import <DOPDropDownMenu.h>
#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import <UIImageView+WebCache.h>
#import "WidthAndHeight.pch"
#import "HTTPTOOL.h"
#import "ClassViewCell.h"
#import "ClassModel.h"
#import "ClassDataViewController.h"
#import "ClassTwoViewController.h"

@interface ClassViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) NSMutableArray *specialArr;  // 专题
@property (nonatomic, retain) MBProgressHUD *HUD;          // 小菊花
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger pageNo;
@property (nonatomic, assign) BOOL isUpLoading;
@property (nonatomic, assign) NSInteger next_Page;

@property (nonatomic, retain) NSString *ClassPath;

@end

@implementation ClassViewController

// 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.specialArr = [NSMutableArray array];
        self.title = @"专题分类";
    }
    return self;
}

// 网络数据请求
- (void)getData:(NSInteger)number;
{
    // 小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];
        
//        NSString *urlStr = [NSString stringWithFormat:@"http://api.bohejiaju.com/v2/collections?limit=50&offset=%ld",number];
//        self.next_Page += 10;
        
        [HTTPTOOL GETWithURL:@ClassViewUrl body:nil httpHead:nil responseStyle:JSON success:^(id result) {
//            if (self.isUpLoading == NO) {
//                [self.specialArr removeAllObjects];
//            }
            /* 3. 写入缓存文件 */
            [result writeToFile:self.ClassPath atomically:YES];
            
            self.specialArr = [[result objectForKey:@"data"] objectForKey:@"collections"];
            
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            [self.collectionView reloadData];
            [self.HUD removeFromSuperview];
            
        } fail:^(NSError *error) {
            NSLog(@"%@", error);
            NSDictionary *dic1 = [NSDictionary dictionaryWithContentsOfFile:self.ClassPath];
            
            self.specialArr = [[dic1 objectForKey:@"data"] objectForKey:@"collections"];
            
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            [self.collectionView reloadData];
            [self.HUD removeFromSuperview];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            /* 添加 action */
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action1];
            /* VC模态推出 alert 界面 */
            [self presentViewController:alert animated:YES completion:^{
                
                [self.HUD removeFromSuperview];
            }];

        }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self collectionViewSubViews];
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenlei"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButton:)];
    
    /* 获取要保存的路径(哪一个文件夹),文件保存到Caches 文件中 */
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    /* 2. 创建文件路径
     * 数组存入本地,若文件名没有后缀,默认市XML 格式
     */
    self.ClassPath = [cachePath stringByAppendingPathComponent:@"class.plist"];
}

// collectionView
- (void)collectionViewSubViews
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置item的大小
    flowLayout.itemSize = CGSizeMake(365 * WIDTH, 150);
    //设置每行item的间隔
    flowLayout.minimumLineSpacing = 20;
    //设置每列item的间隔
    flowLayout.minimumInteritemSpacing = 10;
    //设置滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置item各边的距离(上左下右)
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, VCWIDTH, VCHEIGH - 64) collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[ClassViewCell class] forCellWithReuseIdentifier:@"classViewCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithRed:250 / 255.0 green:245 / 255.0 blue:232 / 255.0 alpha:1];
    [self.view addSubview:self.collectionView];
    // 上啦加载和下拉刷新
    [self addHeader];
//    [self addFooter];
    
    //网络数据请求
    [self getData:0];
}

// collectionView协议方法
// 区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

// 行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.specialArr.count;
}
// item布局
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"classViewCell" forIndexPath:indexPath];
    
    [cell.image sd_setImageWithURL:[NSURL URLWithString:[[self.specialArr objectAtIndex:indexPath.row] objectForKey:@"banner_image_url"]] placeholderImage:[UIImage imageNamed:@"xinqing"]];
    
    
    return cell;
}
// collectionView 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassDataViewController *classData = [[ClassDataViewController alloc] init];
    classData.ID = [[self.specialArr objectAtIndex:indexPath.row] objectForKey:@"id"];
    classData.IDtitle = [[self.specialArr objectAtIndex:indexPath.row] objectForKey:@"title"];
    
    [self.navigationController pushViewController:classData animated:YES];
    
}

// button点击方法
- (void)rightButton:(UIBarButtonItem *)button
{
    ClassTwoViewController *classTwo = [[ClassTwoViewController alloc] init];
    
    [self.navigationController pushViewController:classTwo animated:YES];
    
}


// 刷新
- (void)addHeader
{
    
    [self.collectionView.header beginRefreshing];
    // 添加下拉刷新头部控件
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        __block ClassViewController *vc = self;
        // 进入刷新状态就会回调这个Block
        vc.next_Page = 0;
        vc.isUpLoading = NO;//标记为下拉操作
        
        [vc getData:vc.next_Page];//重新请求数据
        
    }];
    [self.HUD hide:YES afterDelay:5];
}
//// 加载
//- (void)addFooter
//{
//    
//    [self.collectionView.footer beginRefreshing];
//    // 添加上拉刷新尾部控件
//    self.collectionView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
//        
//        __block ClassViewController *vc = self;
//        // 进入刷新状态就会回调这个Block
//        vc.isUpLoading = YES;//标记为上拉操作
//        [vc getData:vc.next_Page];//请求更多数据
//        
//    }];
//    
//    [self.HUD hide:YES afterDelay:5];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
